package com.uplift.mgt.user.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mgt.user.dao.UserMapper;
import com.uplift.mgt.user.model.User;
import com.uplift.mgt.user.service.IUserService;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public List<Map<String, Object>> queryUser(User user) {
		// 不查询超级管理员
		user.setNoAdmin("1");
		PageHelper.startPage(user.getPage(), user.getLimit());
		return this.userMapper.selectUser(user);
	}

	/**
	 * 状态说明，0：账号或密码错误，1：登录成功，2：账号或密码为空，3：被停用
	 */
	@Override
	public int login(HttpServletRequest request, User user) {
		int ret = 0;
		// 判断账号密码是否为空
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			ret = 2;
		} else {
			user.setUsernameEq(user.getUsername());
			user.setUsername(null);
			List<Map<String, Object>> users = this.userMapper.selectUser(user);
			if (users != null && users.size() > 0) {
				Map<String, Object> userMap = users.get(0);
				String status = Objects.toString(userMap.get("status"));
				// 判断是否禁用
				if (StringUtils.equals("0", status)) {
					ret = 3;
				} else {
					request.getSession().setAttribute(Const.SESSION_USER, userMap);
					ret = 1;
				}
			}
		}
		return ret;
	}

	@Override
	public int saveUser(User user) {
		User pUser = new User();
		pUser.setUsernameEq(user.getUsername());
		List<Map<String, Object>> users = this.userMapper.selectUser(pUser);
		if (users != null && users.size() > 0) {
			return 2;
		} else {
			user.setId(UUIDGenerater.generate());
			user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			this.userMapper.insertUser(user);
			return 1;
		}
	}

	@Override
	public int modifyUser(User user) {
		return this.userMapper.updateUser(user);
	}

	@Override
	public int removeUser(User user) {
		String[] idArr = StringUtils.split(user.getId(), ",");
		if(idArr == null || idArr.length == 0) {
			return 0;
		} else {
			user.setIdsList(Arrays.asList(idArr));
			user.setDeleted("1");
			return this.userMapper.deleteUser(user);
		}
	}

}
